package team.first.movieapiv3.controller;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.neo4j.ogm.cypher.BooleanOperator;
import org.neo4j.ogm.cypher.ComparisonOperator;
import org.neo4j.ogm.cypher.Filter;
import org.neo4j.ogm.cypher.Filters;
import org.neo4j.ogm.session.Session;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import team.first.movieapiv3.domain.UserNode;
import team.first.movieapiv3.util.SessionFactoryUtil;
import team.first.movieapiv3.vo.ApiResponse;

import java.util.Collection;

/**
 * @Author: HAPPY
 * @Project_name: project
 * @Package_name: team.first.movieapiv3.controller
 * @Date: 2021/12/9 16:18
 * @Description:
 */
@RestController
public class UserController {

    /**
     * 2.1 POST 用户注册接口
     *
     * @param user 要注册的用户的部分信息
     * @return 返回注册后的用户的全部信息，也就只是多个个自增id
     */
    @PostMapping("/api/v3/register")
    @ApiOperation("2.1 POST 用户注册接口")
    public ApiResponse<UserNode> register(@ApiParam("要注册的用户信息") UserNode user) {
        ApiResponse<UserNode> apiResponse = new ApiResponse<>();
        try {
            Session session = SessionFactoryUtil.getSession("team.first.movieapiv3.domain");
            session.save(user);
            apiResponse.setCode(200).setSuccess(true).setMessage("注册成功").setData(user);
        } catch (Exception e) {
            e.printStackTrace();
            apiResponse.setCode(500).setSuccess(false).setMessage("注册失败").setData(user);
        }
        return apiResponse;
    }

    /**
     * 2.2 用户登录（认证）接口
     *
     * @param user 登录（认证）的用户信息
     * @return 返回认证令牌
     */
    @PostMapping("/api/v3/login")
    public ApiResponse<UserNode> auth(UserNode user) {
        ApiResponse<UserNode> apiResponse = new ApiResponse<>();
        Filters filters = new Filters();
        filters.add(new Filter("email", ComparisonOperator.EQUALS, user.getEmail()));
        Filter filter = new Filter("password", ComparisonOperator.EQUALS, user.getPassword());
        filter.setBooleanOperator(BooleanOperator.AND);
        filters.add(filter);
        Session session = SessionFactoryUtil.getSession("team.first.movieapiv3.domain");
        Collection<UserNode> userNodes = session.loadAll(UserNode.class, filters);

        // 登录成功
        if (userNodes.size() > 0) {
            apiResponse.setCode(200).setSuccess(true).setMessage("登录成功").setData(userNodes.iterator().next());
        } else {
            apiResponse.setCode(500).setSuccess(false).setMessage("登录失败");
        }
        return apiResponse;
    }

}
